#!/usr/bin/php
<?php

/* 
 * Tries to determine if each of the grammars' regular expressions
 * are well formed
 * TODO: test simple rules too.
 */


require_once dirname(__FILE__)  . '/simple_helpers.inc';

define ('SOME_ERR', 0xAAAAAAA);


$EXIT_STATUS = 0;

function test_re($re)
{
  $r = @preg_match($re, '');
  if ($r === false)
    return SOME_ERR;
  return preg_last_error();
}

function test_rule($r)
{
  
  if (!($r->type & LUMINOUS_REGEX))
    return false;
  if ($r->delim_1 !== null)
  {
    if (($e = test_re($r->delim_1)) !== PREG_NO_ERROR)
      return $e;
  }
  if ($r->delim_2 !== null)
  {
    $d = $r->delim_2;
    if ($r->type & LUMINOUS_DYNAMIC_DELIMS)
      $d = '/' . $d;
    if (($e = test_re($d)) !== PREG_NO_ERROR)
      return $e;
  }


  return false;  

}

function test_grammar(LuminousGrammar $g)
{
  global $EXIT_STATUS;
  foreach($g->delimited_types as $i=>$r)
  {
    if (($e = test_rule($r)) !== false)
    {
      $err = ($e === SOME_ERR)? 'Compilation error' : pcre_error_decode($e);
      echo "===Failed\n";
      echo get_class($g) . "\nthrew error: $err\nIn delimiter rule at index $i:\n";
      print_r($r);
      echo "===End\n";
      $EXIT_STATUS = 1;
    }
  }


}




$langs = $luminous_grammars->ListGrammars();

$grammars = array();
foreach($langs as $l)
  test_grammar($luminous_grammars->GetGrammar($l[0]));


exit($EXIT_STATUS);